"use strict"

const fs = require('fs');
const mvc = require("cosjs.mvc");
const handle = mvc.library("handle","下载兑换码","branch/expage")


exports.index = function(){
    let data = {};
    data["cid"] = this.get("cid");
    if(!data["cid"]){
        return this.error("cid empty")
    }
    return handle.index.call(this,data);
}
//游戏服务器列表管理
exports.page = function (){
    let cid = this.get("cid");
    if(!cid){
        return this.error("cid empty")
    }
    let query = {"cid":cid};
    return handle.page.call(this,query);
};

exports.save = function () {
    return handle.save.call(this,getPostData);
}

function getPostData(act,info){
    if(act==='add'){
        info["time"] = Date.now();
        info["status"] = 0;
    }
}

////////////////////////////////下载兑换码//////////////////////////////

exports.download = function () {

    let id = this.get("id")
    if(!id){
        return this.error("id empty")
    }
    this.output = "download";
    let root = this.config.get("root")
    let path = [root,'excode',id+'.txt'].join('/')
    return path;
}



exports.create = function () {
    this.output = "json";
    let id = this.get('id');
    if ( !id ) {
        return this.error('id empty');
    }

    let branch = this.branch;
    let locks = this.model.redis("locks",branch,"excode",30);
    let expage = this.model.branch("expage",branch)

    return locks.start("expage").then(ret=>{
        if(ret.length > 0){
            return this.error("服务器正在生成兑换码，请等待30秒后再生成")
        }
        return expage.get(id);
    }).then(ret=>{
        if(ret["status"]>0){
            return this.error("已经生成，请直接下载")
        }
        return createCode.call(this,branch,ret);
    }).then(ret=>{
        locks.clear();
        return expage.set(id,"status",2);
    }).catch(err=>{
        locks.clear();
        return Promise.reject(err);
    })
}

function createCode(branch,expage) {
    let root = this.config.get("root")
    let path = [root,'excode',expage["_id"]+'.txt'].join('/')

    this.fd = fs.openSync(path,'a+');

    this.seed    = 100;
    this.extime  = parseInt( Date.now() / 1000 );
    this.expage  = expage;
    this.excode  = this.model.branch('excode',branch);
    let task = this.library('multi',expage["num"],createCodeTaskWork.bind(this));
    return task.start().then(()=>{
        fs.close(this.fd,function(){});
    })
}

function createCodeTaskWork(num){
    let roll = this.library("random/Roll",1,9)
    let code = parseInt([roll,this.extime,this.seed + num].join("")).toString(36);
    let data = {"_id": code, "use": 0, "cid": this.expage["cid"],"pid":this.expage["_id"]};
    return this.excode.insert(data).then(()=>{
        return this.library.call(fs,"promise",'appendFile',this.fd,code+"\r\n" )
    }).then(()=>code);
}
